package me.flyray.crm.core.modules.netty.handlers;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.github.wxiaoqi.security.common.util.MD5;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import me.flyray.crm.core.modules.netty.entity.SolidLock;
import net.sf.json.JSONObject;

@Component
@Qualifier("serverHandler")
@Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {

	private static final Logger log = LoggerFactory.getLogger(ServerHandler.class);
	
	@Override
	public void channelRead0(ChannelHandlerContext ctx, String msg)
			throws Exception {
		log.info("服务端收到的消息-client msg:"+msg);
		String clientIdToLong= ctx.channel().id().asLongText();
		log.info("服务端收到的消息-client long id:"+clientIdToLong);
		String clientIdToShort= ctx.channel().id().asShortText();
		log.info("服务端收到的消息-client short id:"+clientIdToShort);
		
		JSONObject jsonObject = JSONObject.fromObject(msg);
        Map<String, String> map = (Map)jsonObject;
        //锁id+++
        String lockId = (String) map.get("lockId");
        
        if (MD5.verify("v-go-icloudpay", (String) map.get("sign"), "", "utf-8")) {
			System.out.println("签名验证通过，建立连接。。。");
			Channel channel = ctx.channel();
			NettyChannelMap.add(lockId,channel);//v-go1 v-go2
			NettyChannelMap.add(clientIdToLong,ctx.channel());
			NettyChannelMap.get(clientIdToLong);
		}
        if(null==LocksMap.get(map.get("lockId"))){
        	//新增锁信息
        	LocksMap.add(map.get("lockId"), new SolidLock(map.get("lockId"), ""));
        }else{
        	//修改锁信息
        	LocksMap.get(map.get("lockId")).setState(map.get("state"));
        	synchronized(LocksMap.get(map.get("lockId"))){
        		LocksMap.get(map.get("lockId")).notify();
        	}
        }
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		
		log.info("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");
		String clientIdToLong= ctx.channel().id().asLongText();
		log.info("client long id:"+clientIdToLong);
		String clientIdToShort = ctx.channel().id().asShortText();
		log.info("client short id:"+clientIdToShort);
//		NettyChannelMap.add("w-lock",(SocketChannel)ctx.channel());
//		NettyChannelMap.add(clientIdToLong,(SocketChannel)ctx.channel());
//		NettyChannelMap.get(clientIdToLong);
//        ctx.channel().writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");
		super.channelActive(ctx);
	}
	
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    	log.info("\nChannel is 异常。。。。。。");
        ctx.close();
    }

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		log.info("\nChannel is disconnected");
		// channel失效，从Map中移除
		NettyChannelMap.remove(ctx.channel());
		super.channelInactive(ctx);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		System.out.println("ServerHandler.channelReadComplete()");
		ctx.flush();
	}
}